package com.demohomework.homeworkdemo.controller;

import com.demohomework.homeworkdemo.pojo.*;
import com.demohomework.homeworkdemo.pojo.Class;
import com.demohomework.homeworkdemo.service.AssAllocationService;
import com.demohomework.homeworkdemo.service.AssSubmitService;
import com.demohomework.homeworkdemo.service.AssignmentService;
import com.demohomework.homeworkdemo.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.demohomework.homeworkdemo.util.RandomUtil;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/assignment")
public class AssignmentController {
    @Autowired
    private AssignmentService assignmentService;
    @Autowired
    private ClassService classService;
    @Autowired
    private AssSubmitService assSubmitService;
    @Autowired
    private AssAllocationService assAllocationService;
    //新增
    @PostMapping("/add")
    public Result add(@RequestBody @Validated({Assignment.Add.class}) Assignment assignment) {
        assignmentService.add(assignment);
        return Result.success();
    }

    //查询作业
    @GetMapping("/list")
    public Result<List<Assignment>> list() {
        List<Assignment> assignments = assignmentService.list();
        return Result.success(assignments);
    }
    //根据id查询作业
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id) {
            Assignment a = assignmentService.findId(id);
            return Result.success(a);
    }
    //根据课程id查询作业
    @GetMapping("/listByCourseId/{courseId}")
    public Result<List<Assignment>> listByCourseId(@PathVariable("courseId") Integer courseId) {
        List<Assignment> assignments = assignmentService.listByCourseId(courseId);
        return Result.success(assignments);
    }
    //更新作业
    @PutMapping("/update")
    public Result update(@RequestBody @Validated(Assignment.Update.class) Assignment assignment){
        assignmentService.update(assignment);
        return Result.success();
    }
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable int id) {
        assignmentService.deleteById(id); // 假设 assignmentService 有 deleteById 方法
        return Result.success();
    }

    //分配作业
    @PostMapping("/assign/{courseId}/{assId}")
    public Result assignReviews(@PathVariable("courseId") Integer courseId, @PathVariable("assId") Integer assId) {
        // 获取所有学生和所有需要批改的作业
        List<Class> students = classService.findByCourseId(courseId); // 获取该课程所有学生
        List<AssSubmit> assignments = assSubmitService.search(assId); // 获取需要批改的作业
        System.out.println("需要批改的作业数量：" + assignments);
        System.out.println("学生数量：" + students);

        if (students.isEmpty() || assignments.isEmpty()) {
            return Result.error("没有找到学生或作业");
        }

        // 每个学生需要批改的作业数量和每份作业需要被多少个不同的人批改
        int reviewCountPerStudent = 5; // 每个学生批改的作业数量
        int reviewersPerAssignment = 5; // 每份作业审核者数量

        // 记录每份作业的审核者数量
        Map<Integer, Integer> assignmentReviewerCount = assignments.stream()
                .collect(Collectors.toMap(AssSubmit::getId, assignment -> 0));

        // 开始分配任务
        Random random = new Random();
        for (int i = 0; i < Math.min(students.size(), assignments.size() * reviewersPerAssignment / reviewCountPerStudent); i++) {
            Class student = students.get(i % students.size());

            // 当前学生已分配的作业
            Set<Integer> assignedAssignments = new HashSet<>();
            while (assignedAssignments.size() < reviewCountPerStudent && assignmentReviewerCount.values().stream().anyMatch(count -> count < reviewersPerAssignment)) {
                // 随机选择一个作业
                List<AssSubmit> availableAssignments = assignments.stream()
                        .filter(assignment -> !Integer.valueOf(student.getId()).equals(assignment.getStuId())) // 学生不能批改自己的作业
                        .filter(assignment -> !assignedAssignments.contains(assignment.getId())) // 学生不能重复批改同一份作业
                        .filter(assignment -> assignmentReviewerCount.get(assignment.getId()) < reviewersPerAssignment) // 作业审核者数量未满
                        .collect(Collectors.toList());
                if (availableAssignments.isEmpty()) {
                    break;
                }
                AssSubmit assignment = availableAssignments.get(random.nextInt(availableAssignments.size()));
                AssAllocation task = new AssAllocation();
                task.setAssId(assignment.getId()); // 作业ID
                task.setAssClass(assignment.getAssId());//作业类别
                task.setStuId(Integer.valueOf(student.getStuId())); // 学生ID
                task.setStatus(0); // 任务状态设置为0
                task.setCreatedAt(LocalDateTime.now()); // 创建时间
                task.setUpdatedAt(LocalDateTime.now()); // 更新时间

                // 立即保存任务到数据库
                assAllocationService.save(task);
                assignedAssignments.add(assignment.getId()); // 添加到已分配作业中
                assignmentReviewerCount.put(assignment.getId(), assignmentReviewerCount.get(assignment.getId()) + 1); // 更新审核者数量
            }
        }
        return Result.success();
    }
}

